package com.ruoyi.web.controller;

import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.Task;
import com.ruoyi.system.domain.TaskUserMark;
import com.ruoyi.system.service.ITaskService;
import com.ruoyi.system.service.ITaskUserMarkService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.TaskLine;
import com.ruoyi.system.service.ITaskLineService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 测评任务明细Controller
 * 
 * @author ruoyi
 * @date 2024-05-19
 */
@RestController
@RequestMapping("/system/line")
public class TaskLineController extends BaseController
{
    @Autowired
    private ITaskLineService taskLineService;

    @Resource
    private ITaskUserMarkService taskUserMarkService;

    @Resource
    private ITaskService taskService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 查询测评任务明细列表
     */
    @PreAuthorize("@ss.hasPermi('system:line:list')")
    @GetMapping("/list")
    public TableDataInfo list(TaskLine taskLine)
    {
        startPage();
        List<TaskLine> list = taskLineService.selectTaskLineList(taskLine);
        return getDataTable(list);
    }

    /**
     * 查询测评任务明细列表
     */
    @PreAuthorize("@ss.hasPermi('system:line:mylist')")
    @GetMapping("/mylist")
    public TableDataInfo myList(TaskLine taskLine)
    {
        startPage();
        List<TaskLine> list = taskLineService.selectMyTaskLineList(taskLine);
        return getDataTable(list);
    }

    /**
     * 导出测评任务明细列表
     */
    @PreAuthorize("@ss.hasPermi('system:line:export')")
    @Log(title = "测评任务明细", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TaskLine taskLine)
    {
        List<TaskLine> list = taskLineService.selectTaskLineList(taskLine);
        ExcelUtil<TaskLine> util = new ExcelUtil<TaskLine>(TaskLine.class);
        util.exportExcel(response, list, "测评任务明细数据");
    }

    /**
     * 获取测评任务明细详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:line:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(taskLineService.selectTaskLineById(id));
    }

    /**
     * 新增测评任务明细
     */
    @PreAuthorize("@ss.hasPermi('system:line:add')")
    @Log(title = "测评任务明细", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TaskLine taskLine)
    {
        return toAjax(taskLineService.insertTaskLine(taskLine));
    }

    /**
     * 修改测评任务明细
     */
    @PreAuthorize("@ss.hasPermi('system:line:edit')")
    @Log(title = "测评任务明细", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TaskLine taskLine)
    {
        return toAjax(taskLineService.updateTaskLine(taskLine));
    }

    /**
     * 对测评任务进行打分
     */
    @PreAuthorize("@ss.hasPermi('system:line:grade')")
    @Log(title = "测评任务明细", businessType = BusinessType.UPDATE)
    @PutMapping("/grade")
    public AjaxResult grade(@RequestBody TaskLine taskLine)
    {
        Long userId = SecurityUtils.getUserId();
        if (SecurityUtils.getLoginUser().getUser().getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toSet()).contains(1L)) {
            throw new ServiceException("管理员不能进行打分");
        }
        String exit = stringRedisTemplate.opsForValue().get(userId + "EXIT");
        if (exit == null) {
            throw new ServiceException("请先查看附件信息");
        }
        String xxx = stringRedisTemplate.opsForValue().get(String.valueOf(userId));
        if (xxx != null) {
            throw new ServiceException("请先浏览五秒");
        }
        // 获取任务明细Id
        Long taskLineId = taskLine.getId();
        // 获取任务明细的详细信息
        TaskLine inDb = taskLineService.selectTaskLineById(taskLineId);
        // 获取评分人信息
        SysUser currentUser = SecurityUtils.getLoginUser().getUser();
        // 获取测评任务
        Task task = taskService.selectTaskById(inDb.getTaskId());
        // 判断是否有效期内
        Date startTime = task.getStartTime(); // 开始时间
        Date endTime = task.getEndTime(); // 结束时间
        if (startTime.compareTo(new Date()) > 0) {
            throw new ServiceException("打分时间尚未开始");
        }
        if (endTime.compareTo(new Date()) < 0) {
            throw new ServiceException("打分时间已经结束");
        }
        // 查询当前用户有没有打分了 如果打分了 就不可以在打分了
        TaskUserMark taskUserMark = new TaskUserMark();
        taskUserMark.setTaskId(task.getId());
        taskUserMark.setJudgmentId(SecurityUtils.getUserId());
        List<TaskUserMark> taskUserMarks = taskUserMarkService.selectTaskUserMarkList(taskUserMark);
        Set<Long> judgmentIdSet = taskUserMarks.stream().map(TaskUserMark::getJudgmentId).collect(Collectors.toSet());
        if (judgmentIdSet.contains(currentUser.getUserId())) {
            throw new ServiceException("您已经打分, 请不要重复提交");
        }
        // 开始构造打分详情
        taskUserMark.setTaskName(task.getTaskName());
        taskUserMark.setUserId(inDb.getUserId());
        taskUserMark.setUserName(inDb.getUserName());
        taskUserMark.setJudgmentId(currentUser.getUserId());
        taskUserMark.setJudgmentName(currentUser.getUserName());
        // 角色信息 一个用户只有一个角色
        SysRole sysRole = currentUser.getRoles().get(0);
        taskUserMark.setJudgmentRole(sysRole.getRoleName());
        // 计算得分
        taskUserMark.setGrade(taskLine.getGrade());
        taskUserMark.setCreateTime(new Date());
        taskUserMark.setUpdateTime(new Date());
        taskUserMarkService.insertTaskUserMark(taskUserMark);

        stringRedisTemplate.delete(userId + "EXIT");
        return toAjax(1);
    }

    /**
     * 删除测评任务明细
     */
    @PreAuthorize("@ss.hasPermi('system:line:remove')")
    @Log(title = "测评任务明细", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(taskLineService.deleteTaskLineByIds(ids));
    }
}
